package com.kaoshi.myweb.snippet.mq.rabbitmq.spring.integration;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractJsonMessageConverter;
import org.springframework.amqp.support.converter.ClassMapper;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.MessageConversionException;

import java.io.IOException;

/**
 * Created by ZHOUTIEQIANG053 on 2017-03-06.
 */
public class FastJSONMessageConverter extends AbstractJsonMessageConverter {
    private static Log log = LogFactory.getLog(FastJSONMessageConverter.class);
    private static ClassMapper classMapper =  new DefaultClassMapper();

    public Object fromMessage(Message message) throws MessageConversionException {
        Object content = null;
        MessageProperties properties = message.getMessageProperties();
        if(properties != null) {
            String contentType = properties.getContentType();
            if(contentType != null && contentType.contains("json")) {
                String encoding = properties.getContentEncoding();
                if(encoding == null) {
                    encoding = this.getDefaultCharset();
                }

                try {
                    String contentAsString = new String(message.getBody(), encoding);
                    Class<?> targetClass = getClassMapper().toClass(message.getMessageProperties());
                    content = JSONObject.parseObject(contentAsString, targetClass);
                } catch (IOException var7) {
                    throw new MessageConversionException("Failed to convert Message content", var7);
                }
            } else {
                log.warn("Could not convert incoming message with content-type [" + contentType + "]");
            }
        }

        if(content == null) {
            content = message.getBody();
        }

        return content;
    }

    protected Message createMessage(Object objectToConvert, MessageProperties messageProperties) throws MessageConversionException {
        Object bytes = null;

        byte[] bytes1;
        try {
            String e = JSONObject.toJSONString(objectToConvert);
            bytes1 = e.getBytes(this.getDefaultCharset());
        } catch (IOException var5) {
            throw new MessageConversionException("Failed to convert Message content", var5);
        }

        messageProperties.setContentType("application/json");
        messageProperties.setContentEncoding(this.getDefaultCharset());
        if(bytes1 != null) {
            messageProperties.setContentLength((long)bytes1.length);
        }
        return new Message(bytes1, messageProperties);
    }
}